import yaml
import datetime,time
from datetime import datetime
import akshare as ak
import requests
import redis
import logging
import pandas as pd
import configparser
from sqlalchemy import create_engine, DateTime, String
import pymysql
pymysql.install_as_MySQLdb()


class Tools:

    @staticmethod
    def get_http_proxy():
        # 指定URL
        url = "http://v2.api.juliangip.com/company/postpay/getips"

        # 定义查询参数
        params = {
            'auto_white': 1,
            'num': 1,
            'pt': 1,
            'result_type': 'text',
            'split': 1,
            'trade_no': '6450380218820899',
            'sign': '9a640362e8baf6a9ee9eaf33f3871e2e'
        }

        # 发送GET请求
        response = requests.get(url, params=params)

        # 检查响应状态码
        if response.status_code == 200:
            # 打印响应内容
            print("Response Content:", response.text)
            return response.text
        else:
            # 打印错误信息
            print("Failed to retrieve data. Status code:", response.status_code)

    @staticmethod
    def get_redis_connect():
        # 初始化配置解析器
        config = configparser.ConfigParser()

        # 读取配置文件
        import os
        current_dir = os.path.dirname(os.path.abspath(__file__))
        config.read(current_dir+'/config.ini')

        redis_host = config.get('Redis', 'host')
        redis_port = config.getint('Redis', 'port')
        redis_db = config.getint('Redis', 'db')
        redis_password = config.get('Redis', 'password')
        r = redis.Redis(host=redis_host, port=redis_port, db=redis_db, password=redis_password)
        return r

    @staticmethod
    def get_mysql_connect():
        # 初始化配置解析器
        config = configparser.ConfigParser()

        # 读取配置文件
        import os
        current_dir = os.path.dirname(os.path.abspath(__file__))
        config.read(current_dir+'/config.ini')

        mysql_port = config.getint('mysql', 'port')
        mysql_host = config.get('mysql', 'host')
        mysql_db = config.get('mysql', 'db')
        import urllib.parse
        mysql_password = urllib.parse.quote(config.get('mysql', 'password'))
        mysql_user = config.get('mysql', 'user')
        db_url = f'mysql://{mysql_user}:{mysql_password}@{mysql_host}:{mysql_port}/{mysql_db}'
        engine = create_engine(db_url,pool_size=20,max_overflow=20,pool_recycle=60)
        return engine
        
    @staticmethod
    def set_log_level(self, level = logging.INFO):
        logging.basicConfig(level=level,  # 设置日志级别，可以根据需要调整为 DEBUG、WARNING 等
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        
    
    @staticmethod
    def get_current_date():
        return datetime.now().strftime('%Y%m%d')
    
    
    @staticmethod
    def count_trading_days(start_date, end_date):
        """
        计算两个日期之间的交易日数量。
        :param start_date: 开始日期，格式为 'YYYYMMDD'
        :param end_date: 结束日期，格式为 'YYYYMMDD'
        :param trade_dates: 交易日列表
        :return: 交易日数量
        """
        # 将日期字符串转换为 datetime 对象
        start_dt = datetime.strptime(start_date, '%Y%m%d').date()
        end_dt = datetime.strptime(end_date, '%Y%m%d').date()
        trade_dates = ak.tool_trade_date_hist_sina()
        trade_dates = trade_dates['trade_date'].tolist()
        
        
        # 过滤出在指定日期范围内的交易日
        filtered_trade_dates = [date for date in trade_dates if start_dt <= date <= end_dt]

        # 返回交易日数量
        return len(filtered_trade_dates)

    #获取前一个交易日
    @staticmethod
    def get_pre_trade_date(trade_date):
        tool_trade_date_hist_sina_df = ak.tool_trade_date_hist_sina()
        date_df = tool_trade_date_hist_sina_df[tool_trade_date_hist_sina_df["trade_date"]< pd.Timestamp(trade_date).date()]
        date_df = date_df.sort_values(by="trade_date",ascending=False)
        pre_trade_date = date_df["trade_date"].values[0]
        return pre_trade_date.strftime("%Y%m%d")

    #格式化输出日期
    @staticmethod
    def format_trade_date(trade_date, from_format,to_format):
        date_obj = datetime.strptime(trade_date,from_format)
        formatted_date = date_obj.strftime(to_format)
        return formatted_date 
    
    def __popup_and_proceed():
        # 创建一个主窗口，但我们不会显示它
        root = tk.Tk()
        root.withdraw()  # 隐藏主窗口

        # 显示消息框
        messagebox.showinfo("提示", "登录同花顺专业版后继续")

        # 关闭主窗口
        root.destroy()
    
    #获取问财cookie
    @staticmethod
    def get_wencai_cookie(force = False):
        r = Tools.get_redis_connect()
        cookie = r.get("wencai_cookie")
        if cookie is not None and force == False:
            return cookie
        
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=False)
            js= """
                    Object.defineProperties(navigator, {webdriver:{get:()=>undefined}});
                """
            
            page = browser.new_page()
            page.add_init_script(js)

            # 访问并生成cookies的操作...
            page.goto('https://www.iwencai.com/unifiedwap/home/index')
            time.sleep(0.2)
            page.get_by_text("注册 / 登录").first.click()
            time.sleep(1)
            
            page.wait_for_selector("#login_iframe")
            iframe_frame = page.frame(name="login_iframe")
            iframe_frame.wait_for_selector('text=密码登录')
            iframe_frame.click('text=密码登录')
            
            time.sleep(1)
            iframe_frame.fill('#uname', 'mo_327559672')
            iframe_frame.fill('#passwd', 'DRC123bank')
            time.sleep(0.5)
            iframe_frame.click('.submit_btn')
            # page.get_by_text("注册 / 登录").first.click()
            # ...登录或其他操作...
            Tools.__popup_and_proceed()
            # 获取并保存cookies到Redis
            cookies =page.context.cookies()
            cookies_str ="; ".join([f"{cookie['name']}={cookie['value']}" for cookie in cookies])
            # pickled_df = pickle.dumps(cookies_str)
            
            r.set('wencai_cookie', cookies_str)
            return cookies_str
            
            
if __name__ == "__main__":
    # start_date = '20230101'
    # end_date = '20230131'
    # trading_days_count = Tools.count_trading_days(start_date, end_date)
    # print("交易日数量:", trading_days_count)
    print(Tools.get_http_proxy())